package org.okwangxing.vsearch.spring;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class VSearchApplicationContext extends ClassPathXmlApplicationContext {
	public static final Logger log = LoggerFactory.getLogger(VSearchApplicationContext.class);
	private ConfigurableApplicationContext applicationContext;

	@Autowired
	private ExtJarResourceLoader extJarResourceLoader;

	public VSearchApplicationContext(String instanceDir, String path) {
		extJarResourceLoader = new ExtJarResourceLoader(instanceDir);
		log.info("加载外围jar包中的spring-beans");
		applicationContext = new ClassPathXmlApplicationContext(path){

			@Override
			public void setClassLoader(ClassLoader classLoader) {
				super.setClassLoader(extJarResourceLoader.getClassLoader());
			}
			
		};
	}

	@Override
	public ClassLoader getClassLoader() {
		return extJarResourceLoader.getClassLoader();
	}

	@Override
	public void setClassLoader(ClassLoader classLoader) {
		super.setClassLoader(extJarResourceLoader.getClassLoader());
	}

	public Class<?> loadClass(String name) throws ClassNotFoundException {
		return extJarResourceLoader.getClassLoader().loadClass(name);
	}

	// /**
	// * 实现ApplicationContextAware接口的回调方法，设置上下文环境
	// */
	// public void setApplicationContext(ApplicationContext applicationContext)
	// throws BeansException {
	// this.applicationContext = (ConfigurableApplicationContext)
	// applicationContext;
	// }
	//
	// public ConfigurableApplicationContext getApplicationContext() {
	// return applicationContext;
	// }

	/**
	 * 获取对象 这里重写了bean方法，起主要作用
	 * 
	 * @param name
	 * @return Object 一个以所给名字注册的bean的实例
	 * @throws BeansException
	 */
	public Object getBean(String beanId) throws BeansException {
		return applicationContext.getBean(beanId);
	}

	/**
	 * @return the extJarResourceLoader
	 */
	public ExtJarResourceLoader getExtJarResourceLoader() {
		return extJarResourceLoader;
	}

	/**
	 * @param extJarResourceLoader
	 *            the extJarResourceLoader to set
	 */
	public void setExtJarResourceLoader(ExtJarResourceLoader extJarResourceLoader) {
		this.extJarResourceLoader = extJarResourceLoader;
	}

}
